from datetime import datetime
from werkzeug.security import generate_password_hash,check_password_hash

from info import constants
from info import db

class BaseModle(object):
    """模型基类，为每个模型补充创建时间"""
    creat_time =db.Column(db.DateTime,default=datetime.now)#记录创建时间
    update_time = db.Column(db.DateTime,default=datetime.now,onupdate=datetime.now)#记录更新时间


#用户收藏表，建立用户与其他收藏新闻多对多的关系
tb_user_colletion=db.Table(
    'info_ user_colletion',
    db.Column('user_id',db.Integer,db.ForeignKey('info_user.id'),primary_key=True),
    db.Column('news_id',db.Integer,db.ForeignKey('info_news.id'),primary_key=True),
    db.Column('create_time',db.DateTime,default=datetime.now)#收藏创建时间
)

tb_user_follows=db.Table(
    'info_user_fans',
    db.Column('follower_id',db.Integer,db.ForeignKey('user.id')),#粉丝id
    db.Column('followed_id',db.Integer,db.ForeignKey('user.id'))#被关注人的id
)

class User(BaseModle,db.Model):
    __tablename__ = 'info_user'
    id = db.Column(db.Integer,primary_key=True) #用户编号
    nick_name = db.Column(db.String(32),unique=True,nullable=False)#用户昵称
    password_hash = db.Column(db.String(128),nullable=False)#加密的密码
    mobile = db.Column(db.String(11),unique=True,nullable=False)#手机号
    avatar_url = db.Column(db.String(256))#用户头像url地址
    last_login = db.Column(db.DateTime,datetime=datetime.now)#最后登录时间
    is_admin = db.Column(db.Boolean,default=False)
    signature = db.Column(db.String(521))#用户签名
    gender = db.Column( #用户性别
        db.Enum(
            'MAN',#男
            'WOMAN'#女
    ),default='MAN')

    #当前用户收藏的所有新闻
    colletion_news = db.relationship('News',sencondary=tb_user_colletion,lazy='dynamic')
    #用户所有的粉丝，添加反向引用followed,代表用户都关注了哪些人
    followers = db.relationship('User',secondary=tb_user_follows,
                                primaryjoin=tb_user_follows.c.followed_id,
                                seconderyjoin=tb_user_follows.c.follower_id,
                                backref=db.backref('followed',lazy='dynamic'),
                                lazy='dynamic'
                                )
    #当前用户所发布的新闻
    news_list = db.relationship('News',backref='user',lazy='dynamic')


    @property
    def password(self):
        raise AttributeError('当前属性不可读')

    @password.setter
    def password(self,value):
        self.password_hash =generate_password_hash(value)

    def check_password(self,password):
        return check_password_hash(self.password_hash,password)

    def to_dict(self):
        resp_dict={
            "id": self.id,
            "nick_name": self.nick_name,
            "avatar_url": self.avatar_url,
            "mobile": self.mobile,
            "gender": self.gender,
            "singature": self.signature,
            "followers": self.followers,
            "news_count": self.news_list.count()
        }
        return resp_dict


    def to_admin_dict(self):
        resp_dict = {
            "id": self.id,
            "nick_name": self.nick_name,
            "mobile": self.mobile,
            "register": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "last_login": self.last_login.strftime("%Y-%m-%d %H:%M:%S"),
        }
        return resp_dict


class News(BaseModle,db.Model):
    #新闻
    __tablename__="info_news"
    id = db.Column(db.Integer, primary_key=True) #新闻编号
    title = db.Column(db.String(256), nullable=False) #新闻标题
    source = db.Column(db.String(64), nullable=False) #新闻来源
    digest = db.Column(db.String(512), nullable=False) #新闻摘要
    content = db.Column(db.Text, nullable=False) #新闻内容
    clicks = db.Column(db.Integer, default=0) #新闻点击量
    index_image_url = db.Column(db.String(256)) #新闻列表图片路径
    category_id = db.Column(db.Integer, db.ForeignKey('info_category.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('info_user.id')) # 当前新闻作者的id
    status = db.Column(db.Integer, default=0) #当前新闻状态 如果为0代表审核通过， 1代表审核中，-1代表审核不通过
    reason = db.Column(db.String(256))  #新闻审核不通过的原因，status = -1的时候使用
    comments = db.relationship('Comment',lazy='dynamic') #当前新闻的所有评论

    def to_review_dict(self):
        resp_dict = {
            "id": self.id,
            "title": self.title,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "status": self.status,
            "reason": self.reason if self.reason else ""
        }
        return resp_dict

    def to_basic_dict(self):
        resp_dict = {
            "id": self.id,
            "title": self.title,
            "source": self.source,
            "digest": self.digest,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "index_image_url": self.index_image_url,
            "clicks": self.clicks,
        }
        return resp_dict

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "title": self.title,
            "source": self.source,
            "digest": self.digest,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "content": self.content,
            "comments_count": self.comments.count(),
            "clicks": self.clicks,
            "category": self.category.to_dict(),
            "index_image_url": self.index_image_url,
            "author": self.user.to_dict() if self.user else None
        }
        return resp_dict


class Comment(BaseModle, db.Model):
    __tablename__="info_comment"
    id = db.Column(db.Integer, primary_key=True) #评论编号
    user_id = db.Column(db.Integer, db.ForeignKeyI('info_user.id'), nullable=False) #用户id
    news_id = db.Column(db.Integer, db.ForeignKey("info_news.id"), nullable=False) #新闻id
    content = db.Column(db.Text, nullable=False) #评论内容
    parent_id = db.Column(db.Integer, db.ForeignKey("info_comment.id")) #父类评论id
    parent = db.relationship("Comment",remote_side=[id]) #自关联
    like_count = db.Column(db.Integer, default=0) #点赞次数

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "content": self.content,
            "parent": self.parent.to_dict() if self.parent else None,
            "user": User.query.get(self.user_id).to_dict(),
            "news_id": self.news_id,
            "like_count": self.like_count
        }
        return resp_dict

class CommentLike(BaseModle, db.Model):
    """评论点赞"""
    __tablename__ = "info_commentlike"
    comment_id = db.Column("comment_id", db.Integer, db.ForeignKey("info_comment.id"), primary_key=True) #评论编号id
    user_id = db.Column("user_id", db.Integer, db.ForeignKey("ino_user.id"),primary_key=True) #用户id


class Category(BaseModle, db.Model):
    """新闻分类"""
    __tablename__ = "info_category"
    id = db.Column(db.Integer, primary_key=True) #分类id
    name = db.Column(db.String(64),nullable=False) #分类名
    news_list = db.relationship("News", backref="category", lazy="dynamci")

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "name": self.name
        }
        return resp_dict